import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution15 {
    public static List<List<Integer>> ret;
    public static List<Integer> path;
    public static boolean[] check;
    public static List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        ret = new ArrayList<>();
        path = new ArrayList<>();
        check = new boolean[nums.length];
        dfs(nums);
        return ret;
    }

    public static void dfs(int[] nums) {
        if(path.size() == nums.length) {
            ret.add(new ArrayList<>(path));
            return;
        }
        for(int i = 0; i < nums.length; i++) {
            //只关心不合法
            if(check[i] == true || (i != 0 && nums[i] == nums[i-1] && check[i-1] == false)) continue;
            path.add(nums[i]);
            check[i] = true;
            dfs(nums);
            path.remove(path.size()-1);
            check[i] = false;

            //只关心合法剪枝
            //if(check[i] == false && (i == 0 || nums[i] != nums[i-1] || check[i-1] == true)) {
                //     path.add(nums[i]);
                //     check[i] = true;
                //     dfs(nums);
                //     path.remove(path.size()-1);
                //     check[i] = false;
                // }
        }
    }

}